import { useMemo, useEffect } from 'react';
import useLatest from './use-latest';
import useUnmount from './use-unmount';
import { isFunction } from '../utils';
import { debounce } from '../utils/debounce';

function useDebounceFn(fn, options) {
  if (process.env.NODE_ENV === 'development') {
    if (!isFunction(fn)) {
      console.log(
        'useDebounceFn',
        `expected parameter is a function, got ${typeof fn}`
      );
    }
  }

  const fnRef = useLatest(fn);

  const wait = options ? options.wait : 1000;

  const debounced = useMemo(() => {
    return debounce(
      (...args) => {
        return fnRef.current(...args);
      },
      wait,
      options
    );
  }, []);

  useUnmount(() => {
    debounced.cancel();
  });

  return {
    run: debounced,
    cancel: debounced.cancel,
    flush: debounced.flush,
  };
}

export default useDebounceFn;
